package top.igotcha.chapter.chapter7;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author Gotcha
 * @date 2021/3/12
 * @describe
 */
public class SubmitTest {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService pool = Executors.newFixedThreadPool(3);
      //  submitTest(pool);
      //  invokeAllTest(pool);
        invokeAnyTest(pool);

    }

    public static void submitTest(ExecutorService pool) throws ExecutionException, InterruptedException {
        Future<String> future = pool.submit(() -> {
            System.out.println("开始运行");
            Thread.sleep(1000);
            return "OK";
        });
        System.out.println(future.get());
    }

    public static void invokeAllTest(ExecutorService pool) throws ExecutionException, InterruptedException {
        List<Future<String>> futures = pool.invokeAll(Arrays.asList(
                () -> {
                        System.out.println("任务1开始运行");
                        Thread.sleep(1000);
                        return "任务1OK";
                    },
                () -> {
                    System.out.println("任务2开始运行");
                    Thread.sleep(500);
                    return "任务2OK";
                    },
                () -> {
                    System.out.println("任务3开始运行");
                    Thread.sleep(2000);
                    return "任务3OK";
                }
            )
        );
        futures.forEach((future)-> {
            try {
                System.out.println(future.get());
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
            }
        });
    }

    public static void invokeAnyTest(ExecutorService pool) throws ExecutionException, InterruptedException{
        String result = pool.invokeAny(Arrays.asList(
                () -> {
                    System.out.println("任务1开始运行");
                    Thread.sleep(1000);
                    return "任务1OK";
                },
                () -> {
                    System.out.println("任务2开始运行");
                    Thread.sleep(500);
                    return "任务2OK";
                },
                () -> {
                    System.out.println("任务3开始运行");
                    Thread.sleep(2000);
                    return "任务3OK";
                }
        ));
        System.out.println(result);
    }
}
